package com.springday3aop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class MyAdvice2 {
    @Pointcut("execution(* com.springday3aop.dao.BookDao.findName(..))")
    private void pt() {
    }

    ;

    //    @Before("pt()")
    public void before(JoinPoint jp) {
//        获取参数
        Object[] args = jp.getArgs();
        System.out.println(Arrays.toString(args));
        System.out.println("before advice ...");
    }

    //    @After("pt()")
    public void after() {
        System.out.println("after advice ...");
    }

    //    around获取参数和返回值
    //    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
//        获取参数
        Object[] args = pjp.getArgs();
        System.out.println("around" + Arrays.toString(args));
//        修改参数
        args[0] = 666;
        Object ret = pjp.proceed(args);
//        获取返回值
        System.out.println(ret);
        return ret;
    }

    //    around获取异常
    //    @Around("pt()")
    public Object around2(ProceedingJoinPoint pjp) {
        Object ret = null;
        try {
            ret = pjp.proceed();
        } catch (Throwable e) {
//            抛出的异常即为获取到的异常
            throw new RuntimeException(e);
        }
        return ret;
    }

    //    returning指定返回值变量名
    @AfterReturning(value = "pt()", returning = "ret")
    public void afterReturning(JoinPoint jp, Object ret) {
//        ret为获取到的返回值
        Object[] args = jp.getArgs();
        System.out.println("afterReturning advice ..." + "参数：" + Arrays.toString(args) + "，返回值：" + ret);
    }

    @AfterThrowing(value = "pt()", throwing = "t")
    public void afterThrowing(Throwable t) {
//        t为获取到的异常
        System.out.println("afterThrowing advice ..." + t);
    }
}
